<?php
//初始化用户信息
function inituser($_mid){
    global $_G;
    //cookie获取用户信息
    $clientkey = getcookie('HeaderKey_'. $_mid);
    //POst过来的用户信息
    $clientkey = $clientkey ? $clientkey : $_GET['HeaderKey'];
    //解密用户信息
    list($auType, $openid, $mid, $subscribe) = explode("\t", SING_auth($clientkey,'DECODE', md5(getglobal('cookiepre','config/cookie').$_SERVER['HTTP_USER_AGENT']) ));
	if($_mid == $mid){
		if($auType == 'wx'){
			$_GET['apifrom'] = 'wx';
			$_G[$_mid]['openid'] = $openid;
			$_G[$_mid]['subscribe'] = $subscribe;
		}
		if($auType == 'app'){
			$_GET['apifrom'] = 'app';
			$_G[$_mid]['memberid'] = $openid;
			//当前登录用户的店铺信息
			$_G[$_mid]['store'] = C::t('#api#store')->getStoreM($_G[$_mid]['memberid']);
		}
		if($auType == 'pc'){
			$_GET['apifrom'] = 'pc';
			$_G[$_mid]['memberid'] = $openid;
			//当前登录用户的店铺信息
			$_G[$_mid]['store'] = C::t('#api#store')->getStoreM($_G[$_mid]['memberid']);
		}
		if($auType == 'outlet'){
			$_GET['apifrom'] = 'outlet';
			$_G[$_mid]['memberid'] = $openid;
		}
	}
	if($_GET['debug1008']){
		$_G[$_mid]['memberid'] = 2147483647;
	}

	//移动端判断
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if(strpos($agent, 'iphone')){
		$_GET['apifrom'] = 'iphone';
	}else if(strpos($agent, 'ipad')){
		$_GET['apifrom'] = 'ipad';
	}else if(strpos($agent, 'android')){
		$_GET['apifrom'] = 'android';
	}else if(strpos($agent, 'html5plus')){
		$_GET['apifrom'] = 'app';
	}else{
		$_GET['apifrom'] = 'unkonw';
	}




        
//        if($_GET['apifrom']=='app'){
//            C::t("D")->WriteLogFile("auType：".$auType.",clientkey：".$clientkey.",get：".json_encode($_GET),"nSign.log","已登录，时间：");
//        }

	//初始化访客信息（账号登录部分）
	C::t('#api#userApi')->ApiInitUser($_mid);
	if(is_array($_GET['id'])) $_GET['id'] = 0;    
    $_G[$_mid]['auType'] = $auType;
    //记录接口日志
    DB::insert("api_log",array(
                    'mid' => $_mid,
                    'class' => $_GET['m'],
                    'method' => $_GET['d'],
                    'sid' => $_GET['id'],
                    'from' => $_GET['apifrom'],
                    'openid' => $_G[$_mid]['openid'],
                    'inputtime' => TIME,
                    'extinfo' => array2string($_GET)
    ));

	/*
	//debug 针对会员 替代身份测试
	$debugMemberIds = array(
			738, //马汉雄
	);
	if(in_array($_G[$_mid]['memberid'],$debugMemberIds)){
		$_G[$_mid]['memberid'] = 803;//沈权
		DB::SetMainDB(DB_MAIN);
		$member = DB::fetch_first('select `openid`,`unionid` from %t where mid=%s and id=%d', array('common_member', $_mid, $_G[$_mid]['memberid']));
		//初始化会员信息
		$_G[$_mid]['openid'] = $member['openid'];
		$_G[$_mid]['unionid'] = $member['unionid'];
		$_G[$_mid]['member'] = C::t('#api#userApi')->getUserBase($_G[$_mid]['memberid'], $_mid);//会员信息
	}
	*/

}
function Api_output(){
    global $_G,$AppId;
    if (defined('SING_OUTPUTED')) {
        return;
    } else {
        define('SING_OUTPUTED', 1);
    }

    $content = ob_get_contents();
    ob_end_clean();

    $_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
    
    $content = str_replace('</head>',"<script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script>\n<script src=\"http://".$AppId.".webwx.sichem.cn/app/weixinjsbridge/?inajax=1&url=".  Api_urlencodebug($_G['FULL_URL'])."\"></script>\n</head>",$content);
    //$jsapi_ticket = GetJsapi_ticket('SPEGEKIGFN');
    //if($jsapi_ticket){
        //$noncestr = createNonceStr();
        //$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        //$buff = array('noncestr'=>$noncestr,'jsapi_ticket'=>$jsapi_ticket,'timestamp'=>TIME,'url'=>$url);
        //$str = formatBizQueryParaMap($buff, false);
       // $_G['jsapi']['signature'] = sha1($str);
   // }
    

   switch($_GET['do']){
		case 'index':
			if($_GET['s'] == 'show'){
				$content = str_replace('</head>','<script>function NewShare(){$.post(\'/app/integral/sharenews\',{id:'.$_GET['id'].'});}</script></head>',$content);
                                $content = str_replace('</head>','<script src="/static/common/js/wx_public.js"></script></head>',$content);//点击量 赞 评论 等公用js
			}
			break;
	}
    echo $content;
}

function Api_urlencodebug($url) {
    $url = str_replace('%26amp%3B', '%26', urlencode($url));
    return $url;
}

function formatBizQueryParaMap($paraMap, $urlencode){
	$buff = "";
	ksort($paraMap);
	foreach ($paraMap as $k => $v)
	{
		if($urlencode)
		{
		   $v = urlencode($v);
		}
		//$buff .= strtolower($k) . "=" . $v . "&";
		$buff .= $k . "=" . $v . "&";
	}
	$reqPar;
	if (strlen($buff) > 0) 
	{
		$reqPar = substr($buff, 0, strlen($buff)-1);
	}
	return $reqPar;
}
function wxThumb($src, $w , $h){
	global $_G;
	
	if(empty($src)) return 'NULL';
	$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(APP_ROOT."/Conf/ue.config.json")), true);
	/*
	* 生成缩略图
	*/
	set_time_limit(0);
	/* 上传配置 */
	$config = array(
		"pathFormat" => $CONFIG['catcherPathFormat'],
		"allowFiles" => $CONFIG['catcherAllowFiles'],
		"path"=>"upload/wx2014/image/{_uid}/{mid}/thumb/".md5($src),
		"width"=>$w,
		"height"=>$h
	);
	if (strpos($src, "http") === 0){
		$item = new Uploader($src, $config, "ossthumb");
	}else{
		$item = new Uploader($src, $config, "thumb");
	}
	
	$info = $item->getFileInfo();
	return $info["url"];
}

function getUser($openid, $mid){
	return C::t('#weixin#user')->get($openid,$mid);	
}

//替换url  这个方法不需要修改 直接复制webfunction里面的 aurl
function aurl($url = '', $mid = ''){
	global $_G;
	if(!trim(strip_tags($url))) return '#';
	//$HOST_URL = SC_MAIN_URL;//主机地址
	$HOST_URL = "http://".$_G['wxapi']['AppId'].SC_WEBWX_URL;
	$PRE1 = 'http://';//http
	//$PRE2 = $HOST_URL.'/app'.$mid.'/';
	$PRE2 = $HOST_URL.'/app/';//2016年8月19日 11:38:57  调整url至wxweb形式
	//要被替换的地址
	$array1 = array(
				$PRE1.'index/show/',
				$PRE1.'index',
				/*--------------------*/
				$PRE1.'member/cancelorder/',
				$PRE1.'member/logistics/',
				$PRE1.'member/orderconfirm/',
				$PRE1.'member/order_detail/',
				$PRE1.'member/order_gift/',
				$PRE1.'member/applyover/',
				$PRE1.'member/cancelapply/',
				$PRE1.'member/applymessage/',
				$PRE1.'member/apply/',
				/*------------------------*/
                $PRE1.'seckill/index',//秒杀首页
				$PRE1.'seckill/loadajax/',
				$PRE1.'member/index/',//会员中心首页
				$PRE1.'member/edit',
				$PRE1.'member/distribution_apply/',
				$PRE1.'member/distribution/',
				$PRE1.'member/collect',
				$PRE1.'member/charge_log',
				$PRE1.'member/orderpai_view/',
				$PRE1.'member/orderpai/',
				$PRE1.'member/pai_log/',
				$PRE1.'member/cash_log/',
				$PRE1.'member/order_view/',
				$PRE1.'member/order_check/',
				$PRE1.'member/order/',
				$PRE1.'member/sign_in',
				$PRE1.'member/integral_list',
				$PRE1.'member/coupon_view/',
				$PRE1.'member/coupon_check/',
				$PRE1.'member/coupon/',
				$PRE1.'member/address/',//收货地址列表
				$PRE1.'member/address_add/',//添加收货地址
				$PRE1.'member/address_edit/',//修改收货地址
				$PRE1.'member/collection/',//我的收藏
				$PRE1.'member/discountvoucher/',//我的收藏
				$PRE1.'member/discountvoucher_view/',//我的收藏
				$PRE1.'member/register/',//会员注册
				$PRE1.'member/login/',//会员登录
				$PRE1.'member',
				$PRE1.'albums?',
				$PRE1.'albums/',
				$PRE1.'album/',
				$PRE1.'list/',
				$PRE1.'news?',
				$PRE1.'news/',
				$PRE1.'form/',
				$PRE1.'card/',
				$PRE1.'scan/',
				$PRE1.'reserve',
				$PRE1.'sign/',
				$PRE1.'eshop/index/',//商城首页
				$PRE1.'eshop/show/',//商城商品详细
				$PRE1.'eshop/cart/',//商城购物车
				$PRE1.'eshop/category/',//商城分类列表
				$PRE1.'eshop/tag/',//商城标签列表
				$PRE1.'eshop/category_navigation/',//商城分类导航
				$PRE1.'eshop/navigation/',//商城导航
				$PRE1.'eshop/search/',//商城筛选
				$PRE1.'eshop/search_ajax/',//商城筛选
				$PRE1.'eshop/seminar/',//商城专题
				$PRE1.'eshop/store_manage/',
				$PRE1.'eshop/store_index/',
				$PRE1.'eshop/surroundings',
				$PRE1.'order/order_getaddr',//订单地址
				$PRE1.'order/order_gift_blessing',//礼物祝福页
				$PRE1.'order/order_gift_send',//礼物分享页
				$PRE1.'order/order_gift_view',//礼物查看页
				$PRE1.'order/order_gift_get',//礼物领取页
				$PRE1.'ggk/',
				$PRE1.'lottery/',
				$PRE1.'active/',
				$PRE1.'cv/',
				$PRE1.'cv?',
				$PRE1.'present_info?',
				$PRE1.'present_get?',
				$PRE1.'present_doget?',
				$PRE1.'present_view?',
				$PRE1.'present_list?',
				$PRE1.'game/',
				$PRE1.'crm/login/',
				$PRE1.'task/index',
				$PRE1.'bonuses/pt/',
				$PRE1.'bonuses/Dbonuses/',
				$PRE1.'bonuses/hblist/',
				$PRE1.'distribution/index/',
				$PRE1.'distribution/apply/',
				$PRE1.'distribution/manage/',
				$PRE1.'distribution/shop/',
            $PRE1.'distribution/myshop/',
				$PRE1.'distribution/edit/',
				$PRE1.'distribution/member/',
            $PRE1.'distribution/deposit/',//店铺验证
				$PRE1.'manifesto/index/',
				$PRE1.'manifesto/makepic/',
				$PRE1.'manifesto/showpic/',
				$PRE1.'sharepage/index/',
				$PRE1.'sharepage/getnum/',
				$PRE1.'sharepage/receiveprize/',
				$PRE1.'survey/index/',
				$PRE1.'survey/show/',
				$PRE1.'survey/rank/',
				$PRE1.'survey/content/',
				$PRE1.'vote/index/',
				$PRE1.'vote/option/',
				$PRE1.'coupon/category/',
				$PRE1.'coupon/show/',
				$PRE1.'coupon/buy/',
				$PRE1.'coupon/pay/',
                $PRE1.'cfund/index',//众筹首页
                $PRE1.'cfund/cfund_detail',//众筹项目详细
                $PRE1.'cfund/support',//众筹 支持列表
                $PRE1.'cfund/support_detail',//众筹 支持详细
                $PRE1.'cfund/my_item',//众筹我的项目与关注
                $PRE1.'cfund/pay',
				$PRE1.'cfund/showMsg',
				$PRE1.'wxpay/index',
				$PRE1.'wxpay/helppayapply/',
				$PRE1.'wxpay/helppay/',
				$PRE1.'wxpay/recharge',
				$PRE1.'cfund/do_ajaxsigned',
            $PRE1.'estate/index',
            $PRE1.'estate/change',
            $PRE1.'estate/login',
            $PRE1.'estate/login_authorize',
            $PRE1.'estate/logout',
            $PRE1.'estate/lead/',
            $PRE1.'garden/index',
            $PRE1.'garden/change',
            $PRE1.'garden/login',
            $PRE1.'garden/login_authorize',
            $PRE1.'garden/logout',
            $PRE1.'garden/outstock_send',
            $PRE1.'park/joinpark',
            $PRE1.'newrss/index/',
            $PRE1.'outlink/index/',
            $PRE1.'webticket/index/',
            $PRE1.'webticket/login/',
			$PRE1.'webticket/accLogin/',
				$PRE1.'outlet/index/',
				$PRE1.'outlet/lead/',
				$PRE1.'outlet/change/',
				$PRE1.'outlet/login/',
				$PRE1.'outlet/login_authorize/',
				$PRE1.'outlet/logout/',
				$PRE1.'outlet/operate/',
				$PRE1.'outlet/scanEwm/',
				$PRE1.'outlet/testScan/',
				$PRE1.'outlet/cart_add/',
				$PRE1.'outlet/order/',
				$PRE1.'outlet/order_ajax/',
				$PRE1.'outlet/order_view/',
				$PRE1.'outlet/order_view_print/',
				$PRE1.'outlet/order_pay/',
				$PRE1.'outlet/order_scan/',
				$PRE1.'outlet/outstock/',
				$PRE1.'outlet/outstock_ajax/',
				$PRE1.'outlet/outstock_send/',
				$PRE1.'outlet/register/',
				$PRE1.'outlet/settle/',
				$PRE1.'outlet/getMember/',
				$PRE1.'outlet/order_refund_ajax',
				$PRE1.'outlet/search_ajax',
				$PRE1.'outlet/goods_attribute',
				$PRE1.'outlet/order_refund',
				$PRE1.'outlet/order_statistics',
				$PRE1.'outlet/order_excel',
				$PRE1.'outlet/order_statistics_excel',
				$PRE1.'outlet/order_statistics_print',
				$PRE1.'outlet/market',
            $PRE1.'repo/index',
            $PRE1.'repo/change',
            $PRE1.'repo/login',
            $PRE1.'repo/login_authorize',
            $PRE1.'repo/logout',
            $PRE1.'repo/lead/',
            $PRE1.'repo/market',
            $PRE1.'repo/order/',
            $PRE1.'repo/order_ajax/',
            $PRE1.'repo/order_view/',
            $PRE1.'repo/order_pay/',
            $PRE1.'repo/order_scan/',
            $PRE1.'repo/outstock/',
            $PRE1.'repo/outstock_ajax/',
            $PRE1.'repo/outstock_send/',
            $PRE1.'repo/outstock_order/',
            $PRE1.'repo/turnsms/',
        $PRE1.'shake/index',
        $PRE1.'shake/count_down',
        $PRE1.'shake/recScore',
        $PRE1.'shake/attention',
        $PRE1.'shake/awards',
        $PRE1.'shake/getRank',
        $PRE1.'shake/baoming',
        $PRE1.'signsort/index',
            $PRE1.'review/addreview',
            $PRE1.'review/reviewafter',
            $PRE1.'review/first',
            $PRE1.'review',
        $PRE1.'chat/send',
		$PRE1.'sms/index/',
		$PRE1.'sms/send/',
		$PRE1.'sms/verify/',
		$PRE1.'store/apply/',
		$PRE1.'store/apply_add/',
		$PRE1.'wxpay/index/'

				);
	$array2 = array(
				$PRE2.'index/show?id=',
				$PRE2.'index',
				/*--------------------*/
				$PRE2.'member/cancelorder/',
				$PRE2.'member/logistics/',
				$PRE2.'member/orderconfirm/',
				$PRE2.'member/order_detail',
				$PRE2.'member/order_gift',
				$PRE2.'member/applyover/',
				$PRE2.'member/cancelapply/',
				$PRE2.'member/applymessage/',
				$PRE2.'member/apply/',
				/*------------------------*/
                $PRE2.'seckill/index',//秒杀首页
				$PRE2.'seckill/loadajax/',
				$PRE2.'member/index',
				$PRE2.'member/edit',
				$PRE2.'member/distribution_apply/',
				$PRE2.'member/distribution/',
				$PRE2.'member/collect',
				$PRE2.'member/charge_log',
				$PRE2.'member/orderpai_view?id=',
				$PRE2.'member/orderpai',
				$PRE2.'member/pai_log?id=',
				$PRE2.'member/cash_log',
				$PRE2.'member/order_view?id=',
				$PRE2.'member/order_check?id=',
				$PRE2.'member/order/',
				$PRE2.'member/sign_in',
				$PRE2.'member/integral_list',
				$PRE2.'member/coupon_view?id=',
				$PRE2.'member/coupon_check?id=',
				$PRE2.'member/coupon',
				$PRE2.'member/address',
				$PRE2.'member/address_add',
				$PRE2.'member/address_edit?id=',
				$PRE2.'member/collection',
				$PRE2.'member/discountvoucher/',
				$PRE2.'member/discountvoucher_view/',
				$PRE2.'member/register',//会员注册
				$PRE2.'member/login',//会员登录册
				$PRE2.'member/index',
				$PRE2.'albums',
				$PRE2.'albums?id=',
				$PRE2.'album?id=',
				$PRE2.'index/category?id=',
				$PRE2.'index/show',
				$PRE2.'index/show?id=',
				$PRE2.'form?id=',
				$PRE2.'card?id=',
				$PRE2.'scan?id=',
				$PRE2.'reserve',
				$PRE2.'sign?id=',
				$PRE2.'eshop/index',
				$PRE2.'eshop/show?id=',
				$PRE2.'eshop/cart',
				$PRE2.'eshop/category?id=',
				$PRE2.'eshop/tag?id=',
				$PRE2.'eshop/category_navigation',
				$PRE2.'eshop/navigation',
				$PRE2.'eshop/search',
				$PRE2.'eshop/search_ajax',
				$PRE2.'eshop/seminar',//商城专题
				$PRE2.'eshop/store_manage/',
				$PRE2.'eshop/store_index?id=',
                $PRE2.'eshop/surroundings',
				$PRE2.'order/order_getaddr',
				$PRE2.'order/order_gift_blessing',//礼物祝福页
				$PRE2.'order/order_gift_send',//礼物分享页
				$PRE2.'order/order_gift_view',//礼物查看页
				$PRE2.'order/order_gift_get',//礼物领取页
				$PRE2.'ggk?id=',
				$PRE2.'lottery?id=',
				$PRE2.'active?id=',
				$PRE2.'cv/index',
				$PRE2.'cv/view?id=',
				$PRE2.'present/present_info?id=',
				$PRE2.'present/present_get?id=',
				$PRE2.'present/present_doget?id=',
				$PRE2.'present/present_view?id=',
				$PRE2.'present/present_list?id=',
				$PRE2.'game?id=',
				$PRE2.'crm/login?ticket=',
				$PRE2.'task/index',
				$PRE2.'bonuses/pt?id=',
				$PRE2.'bonuses/Dbonuses?id=',
				$PRE2.'bonuses/hblist',
				$PRE2.'distribution/index/',
				$PRE2.'distribution/apply/',
				$PRE2.'distribution/manage/',
				$PRE2.'distribution/shop/',
            $PRE2.'distribution/myshop/',
				$PRE2.'distribution/edit/',
				$PRE2.'distribution/member/',
            $PRE2.'distribution/deposit/',//店铺验证
				$PRE2.'manifesto/index?id=',
				$PRE2.'manifesto/makepic?id=',
				$PRE2.'manifesto/showpic?id=',
				$PRE2.'sharepage/index?id=',
				$PRE2.'sharepage/getnum?id=',
				$PRE2.'sharepage/receiveprize?id=',
				$PRE2.'survey/index?id=',
				$PRE2.'survey/show?id=',
				$PRE2.'survey/rank?id=',
				$PRE2.'survey/content?id=',
				$PRE2.'vote/index?id=',
				$PRE2.'vote/option?id=',
				$PRE2.'coupon/category?id=',
				$PRE2.'coupon/show?id=',
				$PRE2.'coupon/buy?id=',
				$PRE2.'coupon/pay?id=',
                $PRE2.'cfund/index',
                $PRE2.'cfund/cfund_detail',
                $PRE2.'cfund/support',
                $PRE2.'cfund/support_detail',
                $PRE2.'cfund/my_item',
                $PRE2.'cfund/pay',
				$PRE2.'cfund/showMsg',
				$PRE2.'wxpay/index',
				$PRE2.'wxpay/helppayapply',
				$PRE2.'wxpay/helppay',
				$PRE2.'wxpay/recharge',
				$PRE2.'cfund/do_ajaxsigned',
            $PRE2.'estate/index',
            $PRE2.'estate/change',
            $PRE2.'estate/login',
            $PRE2.'estate/login_authorize',
            $PRE2.'estate/logout',
            $PRE2.'estate/lead/',
            $PRE2.'garden/index',
            $PRE2.'garden/change',
            $PRE2.'garden/login',
            $PRE2.'garden/login_authorize',
            $PRE2.'garden/logout',
            $PRE2.'garden/outstock_send',
            $PRE2.'park/joinpark',
            $PRE2.'newrss/index/',
            $PRE2.'outlink/index/',
            $PRE2.'webticket/index/',
            $PRE2.'webticket/login/',
			$PRE2.'webticket/accLogin/',
				$PRE2.'outlet/index',
				$PRE2.'outlet/lead',
				$PRE2.'outlet/change',
				$PRE2.'outlet/login',
				$PRE2.'outlet/login_authorize',
				$PRE2.'outlet/logout',
				$PRE2.'outlet/operate',
				$PRE2.'outlet/scanEwm',
				$PRE2.'outlet/testScan',
				$PRE2.'outlet/cart_add',
				$PRE2.'outlet/order',
				$PRE2.'outlet/order_ajax',
				$PRE2.'outlet/order_view?id=',
				$PRE2.'outlet/order_view_print?id=',
				$PRE2.'outlet/order_pay?id=',
				$PRE2.'outlet/order_scan',
				$PRE2.'outlet/outstock',
				$PRE2.'outlet/outstock_ajax',
				$PRE2.'outlet/outstock_send?id=',
				$PRE2.'outlet/register',
				$PRE2.'outlet/settle',
				$PRE2.'outlet/getMember',
				$PRE2.'outlet/order_refund_ajax',
				$PRE2.'outlet/search_ajax',
				$PRE2.'outlet/goods_attribute',
				$PRE2.'outlet/order_refund',
				$PRE2.'outlet/order_statistics',
				$PRE2.'outlet/order_excel',
				$PRE2.'outlet/order_statistics_excel',
				$PRE2.'outlet/order_statistics_print',
				$PRE2.'outlet/market',
            $PRE2.'repo/index',
            $PRE2.'repo/change',
            $PRE2.'repo/login',
            $PRE2.'repo/login_authorize',
            $PRE2.'repo/logout',
            $PRE2.'repo/lead/',
            $PRE2.'repo/market',
            $PRE2.'repo/order/',
            $PRE2.'repo/order_ajax/',
            $PRE2.'repo/order_view/',
            $PRE2.'repo/order_pay/',
            $PRE2.'repo/order_scan/',
            $PRE2.'repo/outstock/',
            $PRE2.'repo/outstock_ajax/',
            $PRE2.'repo/outstock_send/',
            $PRE2.'repo/outstock_order/',
            $PRE2.'repo/turnsms/',
        $PRE2.'shake/index',
        $PRE2.'shake/count_down',
        $PRE2.'shake/recScore',
        $PRE2.'shake/attention',
        $PRE2.'shake/awards',
        $PRE2.'shake/getRank',
        $PRE2.'shake/baoming',
        $PRE2.'signsort/index',
            $PRE2.'review/addreview',
            $PRE2.'review/reviewafter',
            $PRE2.'review/first',
            $PRE2.'review',
        $PRE2.'chat/send',
		$PRE2.'sms/index/',
		$PRE2.'sms/send/',
		$PRE2.'sms/verify/',
		$PRE2.'store/apply/',
		$PRE2.'store/apply_add/',
		$PRE2.'wxpay/index/'
				);//被替换后的地址
	
	$url = str_replace($array1, $array2, $url);
	if(is_weixin()){
            if(strpos($url,"?")){
                $url .= '&sopenid='.$_G[$mid]['openid'];
            }else{
                $url .= '?sopenid='.$_G[$mid]['openid'];
            }
	}
	return $url;
}

/*
	分享数据功能
*/
function toShare($_mid,$_openid,$_table,$_id){
	if(!$_mid || !$_openid || !$_table || !$_id) return false;
	DB::insert('wx_share',array(
								'mid'=>$_mid,
								'openid'=>$_openid,
								'tablename'=>$_table,
								'tableid'=>$_id,
								'inputtime'=>TIME
							)
				);
	return true;
}

/*
	积分设置信息
*/
function integralSetting($_mid){
	
	$r = DB::result_first('select value from %t where mid=%s',array('wx_integral_setting',$_mid));
	
	$array = $r ? json_decode($r,true) : array();
	
	if(!is_array($array)) $array = array();
	
	return $array;
	
}

/*
	单独的积分数据表
	$_mid 			平台id
	$_openid 		要操作积分的用户
	$_table
	$_id 
	$_type 			方式
	$_integral 		积分数
	$_increase 		是否重复添加 1 是 0 否
	$_fromopenid 	来源openid
	$_toopenid 		自身的openid
	$_note 			备注
*/
function plusIntegral($_mid,$_openid,$_table,$_id,$_type,$_field,$_integral,$_increase = 0,$_fromopenid = '',$_toopenid = '',$_note = ''){
	
	if(!$_mid || !$_openid || !$_integral) return false;
	
	$r = DB::result_first('select id from %t where mid=%s and tablename=%s and tableid=%s and from_openid=%s and to_openid=%s and type=%s',array('wx_integral_log',$_mid,$_table,$_id,$_fromopenid,$_toopenid,$_type));
	
	if(!$r || $_increase){
		
		$integral_type = lang('weixin_integral','integral_type');
		
		$_field = in_array($_field,$integral_type) ? $_field : 'value1';
		
		//会员积分信息
		$userinit = DB::fetch_first('select * from %t where mid=%s and openid=%s',array('wx_integral',$_mid,$_openid));
		
		if($userinit['id']){
			$userInit[$_field] = $_integral + $userinit[$_field];
			DB::update('wx_integral',$userInit,'id='.intval($userinit['id']));
		}else{
			$userInit['mid'] = $_mid;
			$userInit['openid'] = $_openid;
			$userInit[$_field] = $_integral;
			DB::insert('wx_integral',$userInit);
		}
		//获取积分设置进行增长相应的积分
		
		$sql['id'] 			= date('YmdHis').rand_str(6,true);
		$sql['_uid'] 		= $_G['_uid'];
		$sql['mid'] 		= $_mid;
		$sql['from_openid'] = $_fromopenid;
		$sql['to_openid'] 	= $_toopenid;
		$sql['tablename'] 	= $_table;
		$sql['tableid'] 	= $_id;
		$sql['type'] 		= $_type;
		$sql[$_field] 		= $_integral;
		$sql['note'] 		= $_note;
		$sql['inputtime'] 	= TIME;
		DB::insert('wx_integral_log',$sql);
		
		//plusGold($_mid,$_openid,$_integral,'jf',$_note,$_table,$_id,$_increase);
		
		return true;
		
	}else return false;
}
/*
	增加或减少余额
	mid      客户标识
	openid   会员标识
	type     类型 ye:余额  jf:积分
	note     备注
	table    表名
	id       对应表id
	increase 是否重复提交(必须有table 和id的时候)
*/
function plusGold($mid,$openid,$amount,$type = 'ye',$note ='',$table = '',$id = 0,$increase = 1){
	global $_G;
	$wxuser = getUser($openid,$mid);
	if(!$wxuser) return false;
	$update = array();
	//余额
	if($type == 'ye'){
		if($amount && is_numeric($amount)){
			if(($amount < 0 && $wxuser['ye'] >= $amount) || $amount > 0){
				$update['ye'] = $wxuser['ye'] + $amount;
				$insert_ye['uid'] = $_G['uid'];
				$insert_ye['mid'] = $mid;
				$insert_ye['openid'] = $openid;
				$insert_ye['type'] = 'ye';
				$insert_ye['amount'] = $amount;
				$insert_ye['inputtime'] = TIME;
				$insert_ye['note'] = $note;
				$insert_ye['tablename'] = $table ? $table : '';
				$insert_ye['tableid'] = $id ? $id : '';
				DB::insert('wx_charge', $insert_ye);
			}else{
				return false;	
			}
		}else{
			return false;	
		}
	}
	//积分
	if($type == 'jf'){
		if($amount && is_numeric($amount)){
			if(($amount < 0 && $wxuser['jf'] >= $amount) || $amount > 0){
				if($table && $id && !$increase){
					$incre = DB::fetch_first('select * from %t where mid=%s and openid=%s and type=%s and tablename=%s and tableid=%d', array('wx_charge',$mid,$openid,'jf',$table,$id));
					if($incre){
						return false;
					}
				}
				$update['jf'] = $wxuser['jf'] + $amount;
				$insert_jf['uid'] = $_G['uid'];
				$insert_jf['mid'] = $mid;
				$insert_jf['openid'] = $openid;
				$insert_jf['type'] = 'jf';
				$insert_jf['amount'] = $amount;
				$insert_jf['inputtime'] = TIME;
				$insert_jf['note'] = $note;
				$insert_jf['tablename'] = $table ? $table : '';
				$insert_jf['tableid'] = $id ? $id : '';
				DB::insert('wx_charge', $insert_jf);
			}else{ 
				return false;	
			}
		}else{
			return false;	
		}
	}
	if(count($update) > 0){
		DB::update('wx_wxuser', $update, "mid='".$mid."' and openid='".$openid."'");
		return true;
	}
	return false;
}


//exit 返回jsonp形式
function exit_jsonp($val,$callback='callback'){
    global $_G;
    if(is_array($val)){
        $val = json_encode($val);
    }
    if($_G['inajax']){
        echo $val;
        exit;
    }
//callback 只能由字母,数字，下划线组成，并且以字母或下划线开头
    if(!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]+$/', $callback)){
        $callback='callback';
    }
    header('Content-type: text/javascript');
    $callback = urlencode($callback); 
    echo "window[decodeURIComponent('{$callback}')]({$val})";
    exit;
}


/*	截取字符串
*	$sourcestr 	需要截取的字符串
*	$cutlength	截取的长度
*	$nohtml		是否带html标签 默认 不带
*	$laststr	截取长度小于字符串长度是 后面加的后缀 默认 ...
*/
function Api_substr_cut_str($sourcestr,$cutlength=0,$nohtml=1,$laststr='...'){	
	if($nohtml) $sourcestr = strip_tags($sourcestr,'');
	$returnstr='';
	$i=0;
	$n=0;
	$str_length=strlen($sourcestr);//字符串的字节数
	while ((($n < $cutlength)||!$cutlength) and ($i <= $str_length)){
		$temp_str=substr($sourcestr,$i,1);
		$ascnum=ord($temp_str);//得到字符串中第$i位字符的ascii码
		if ($ascnum>=224){//如果ASCII位高与224，
			$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
			$i=$i+3; //实际Byte计为3
			$n++; //字串长度计1
		}elseif ($ascnum>=192){//如果ASCII位高与192，
			$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i=$i+2; //实际Byte计为2
			$n++; //字串长度计1
		}elseif ($ascnum>=65 && $ascnum<=90){//如果是大写字母，
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数仍计1个
			$n++; //但考虑整体美观，大写字母计成一个高位字符
		}else{//其他情况下，包括小写字母和半角标点符号，
			$returnstr=$returnstr.substr($sourcestr,$i,1);
			$i=$i+1; //实际的Byte数计1个
			$n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	if ($str_length>$i){
		$returnstr = $returnstr . $laststr;//超过长度时在尾处加上后缀
	}
	return $returnstr; 
}
/*
	php自身生成二维码
	$_content 二维码内容
	$_matrixPointSize 生成图片大小
	$_errorCorrectionLevel 容错级别
*/
function phpQrCode($_content,$_matrixPointSize = 6,$_errorCorrectionLevel = 'L'){
	QRcode::png($_content,false,4,10,2);
}

/*---------------
 * 
 *订单记录
 * $functionname来源方法名   
 * $id 订单id， 
 * $tablename 操作表名,
 * $tableid 操作表id,
 * $note 操作行为  
 * $notice是否通知会员 
 * $extkey 如果存在 $id等于 $tablename下 $extkey字段的值
 * 
 */
function addOrderLog($functionname='',$id='',$tablename='',$tableid='',$note='',$notice=0,$extkey=''){
    global $_G,$mid;
    if(!$functionname || !$id || !$tablename || !$tableid || !$note ){
		//必传值 没有传入  所以 echo  错误
		$str=json_encode(array('functionname'=>$functionname,'id'=>$id,'tablename'=>$tablename,'tableid'=>$tableid,'note'=>$note));
        //echo 'addOrderLog_error';
		echo $str;
        //exit;
    }
    if(is_array($note)){
        $note = json_encode($note);
    }
    $log = array();
    $log['mid'] = $_GET['mid'];
    $log['member_id'] = $_G[$_GET['mid']]['memberid'];
    $log['openid'] = $_G[$_GET['mid']]['openid'];
    $log['inputtime'] = $log['updatetime'] = TIME;
    $log['uid'] = $_G['uid'];
    $log['_uid'] = $_G['_uid'];
    $log['order_id'] = $id;
    $log['fromfunction'] = $functionname;
    $log['fromsite'] = 0;
    $log['tablename'] = $tablename;
    $log['tablekey'] = $extkey;
    $log['tableid'] = $tableid;
    $log['note'] = $note;
    $log['notice'] = $notice;
    $log['clientip'] = $_G['clientip'];
    DB::SetMainDB(DB_ESHOP);
    DB::insert('es_order_log',$log);
}
function web_curl($url,$post_data = array()){		
	$get_content = DoCurl($url, $post_data);
	return json_decode($get_content,true);
}
function Web_urlencodebug($url) {
    $url = str_replace('%26amp%3B', '%26', urlencode($url));
    return $url;
}
function web_GetAccess_token($mid = ''){
	global $_G,$_mid;
	if($mid) $_mid = $mid;
	DB::query("delete FROM %t where mid=%s and `inputtime` <= %d", array('wx_access_token',$_mid ,TIME-6000));
	$token = DB::fetch_first("select `access_token` from %t where mid=%s and `inputtime` > %d", array('wx_access_token',$_mid ,TIME-6000));
	//var_dump($token);
        if($token){
		$access_token = $token['access_token'];
	}else{
		if(!$_G['wxapi']['AppId'] || !$_G['wxapi']['AppSecret']){
			$r = DB::fetch_first('select AppId,AppSecret from %t where mid=%s', array('wx_apiuser', $_mid));
			//var_dump($r);
                        if(!$r) return false;
			$_G['wxapi'] = array('AppId'=>$r['AppId'],'AppSecret'=>$r['AppSecret']);
		}
		$d = web_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$_G['wxapi']['AppId']."&secret=".$_G['wxapi']['AppSecret']);
		//var_dump($d);
                if(is_array($d) && $d['access_token']){
			DB::insert('wx_access_token',	array('access_token'=>$d['access_token'] ,'mid'=>$_mid , 'inputtime'=>TIME ) );
			$access_token = $d['access_token'];
		}else{
			
		}
	}
        
	if($access_token) return $access_token;
	else return false;
}

/*  *
评论自动处理
 *  */
function Review_update($_mid,$_storeid=0){
    if(!$_mid) return false;
    $setiing = C::t('#api#review')->getReviewSettingM($_storeid);
    if($setiing['id'] && $setiing['auto_review_time']){
        $auto_review_time = TIME - $setiing['auto_review_time']; //自动好评时间
        
        //取出未评论的订单详细
        DB::SetMainDB(3);
        $order_detail = DB::fetch_all('SELECT id,order_id,goods_id,openid FROM %t where mid=%s and store_id=%d and comment_status=0 and detail_status=1',array('es_order_detail',$_mid,$_storeid));
        $order_array = array(); //到时间的订单组
        $order_illegal_array = array(); //没有到时间或者无效的订单组
        foreach($order_detail as $k => $v){
            if(!$order_illegal_array[$v['order_id']]){
                continue;
            }
            if(!$order_array[$v['order_id']]){
                $order_array[$v['order_id']] = DB::fetch_all('select `id`,`success_time` from %t '
                        . 'where mid=%s and store_id=%d and openid=%s and id=%s and order_status=1 and success_time<=%d ',array('es_order',$_mid,$_storeid,$v['openid'],$v['order_id'],$auto_review_time));
                if(empty($order_array[$v['order_id']])){
                    $order_illegal_array[$v['order_id']] = 1;
                    continue;
                }
            }
            if($order_array[$v['order_id']]){
                $update_detail = array();
                $update = array();
                $update_detail['comment_status'] = 1;
                $update_detail['updatetime'] = TIME;
                DB::SetMainDB(3);
                DB::update('es_order_detail', $update_detail,'id='.$v['id']);
                addOrderLog(__FUNCTION__,$order_id,'es_order_detail',$k, $update_detail);//记录行为
                $update['inputtime'] = $update['updatetime'] = TIME;
                $update['status'] = 1;
                $update['content'] = '好评！';
                $update['attitude'] = 5;
                $update['openid'] = $v['openid'];
                $update['mid'] = $_mid;
                $update['store_id'] = $_storeid;
                $update['order_id'] = $v['order_id'];
                $update['detail_id'] = $v['id'];
                $update['goods_id'] = $v['goods_id'];
                $update['anonym'] = 1;
                $update['systematic'] = 1;
                $update['systematic_time'] = $order_array[$v['order_id']]['success_time'] + $setiing['auto_review_time'];
                $update['systematic_real_time'] = TIME;
                DB::SetMainDB(3);
                DB::insert('es_order_review', $update);
            }

        }
    }
}

function checkotrigger($mid,$id){
	if(!in_array($mid,array('SPEGEKIGFN','RDOXYKDTTD'))){
		return false;
	}
	if(!$mid || !$id){
		return false;	
	}
	
	
	DB::SetMainDB(DB_ESHOP);
	$order = DB::fetch_first('select openid,order_status,pay_status,send_status,openid,create_time,pay_time,send_time,success_time,total_actual_pay from %t where mid=%s and id=%s',array('es_order',$mid,$id));
	if(!$order){
		return false;	
	}
	
	$x_bool = true;
	
	if($order['pay_status']==1) $p_bool = true;
	else $p_bool = false;
	
	//$s_bool = true;
	
	if($order['order_status']==1) $o_bool = true;
	else $o_bool = false;
	
    DB::SetMainDB(DB_ESHOP);
	$o_handle = DB::fetch_all("select handle from %t where order_id=%s and mid=%s and status=1 and display=1",array("es_otrigger_log",$id,$mid));
	
	
	foreach($o_handle as $success){
		if($success['handle'] == 1){
			$x_bool = false;
		}
		if($success['handle'] == 2){
			$p_bool = false;
		}
		/*if($success['handle'] == 3){
			$s_bool = false;
		}*/
		if($success['handle'] == 4){
			$o_bool = false;
		}
	}
	
	
	if($x_bool){
		insertootriggerlog(1,$order,$mid,$id);
	}
	if($p_bool){
		insertootriggerlog(2,$order,$mid,$id);
	}
	/*if($s_bool){
		insertootriggerlog(3,$order,$mid,$id);
	}*/
	if($o_bool){
		insertootriggerlog(4,$order,$mid,$id);
	}
	
}
//插入订单活动记录
function insertootriggerlog($handle,$order,$mid,$id){
	
	DB::SetMainDB(DB_ESHOP);
    //$oh = DB::fetch_all("select `id`,`title`,`handle`,`time_type`,`btime`,`etime`,`price_type`,`min_price`,`max_price`,`trigger_type`,`trigger_id`,`trigger_other`,`trigger_filed`,`trigger_num`,`limit_group` from %t where mid=%s and handle=%d and status=1 and display=1",array("es_otrigger",$mid,$handle));
	$oih = DB::fetch_all("select `id`,`title`,`handle`,`time_type`,`btime`,`etime` from %t where mid=%s and handle=%d and status=1 and display=1",array("es_otrigger_important",$mid,$handle));
	
	//没有限制是否关注  如果需要之后加上
	$groupid = DB::result_first('select groupid from %t where mid=%s and openid=%s',array('wx_wxuser',$mid,$order['openid']));
   	foreach($oih as $ih){
		$order_time = '';
		$isfalse = 0;
		switch($ih['time_type']){
			case 1:
				$order_time = $order['create_time'];
				break;
			case 2:
				$order_time = $order['pay_time'];
				break;
			case 3:
				$order_time = $order['send_time'];
				break;
			case 4:
				$order_time = $order['success_time'];
				break;
			default:
				$isfalse = 1;
				break;
		}
		if($isfalse){
			continue;	
		}
		if($order_time < $ih['btime'] || $order_time >= $ih['etime']){
			continue;
		}
		
		
		DB::SetMainDB(DB_ESHOP);
		$h = DB::fetch_first("select `id`,`min_price`,`trigger_type`,`trigger_id`,`trigger_other`,`trigger_filed`,`trigger_num`,`limit_group` from %t where mid=%s and important_id=%d and min_price<=%d and (limit_group=-1 or limit_group=%d) and status=1 and display=1 order by min_price desc",array("es_otrigger",$mid,$ih['id'],$order['total_actual_pay'],$groupid));	
		if(!$h){
			continue;	
		}
		$isfalse = 0;
		switch($h['trigger_type']){
			case 'coupon':
				$rcoupon = discountvoucher_get($h['trigger_id'],$mid,$order['openid']);
				$logid = intval($rcoupon['id']);
				break;
			case 'event':
				$revent = trigger_event($h['trigger_id'],$mid,$order['openid']);
				$revent = $revent?json_decode($revent,true):array();
				$revent = is_array($revent) ? $revent : array();
				$logid = intval($revent['activeid']);
				break;
			case 'balance':
				$trigger_num = intval($h['trigger_num']);
				if($trigger_num <= 0){
					$isfalse = 1;
					break;
				}
				$ye = DB::result_first('select ye from %t where mid=%s and openid=%s',array('wx_wxuser',$mid,$order['openid']));
				$ye = $ye + $trigger_num;
				DB::update('wx_wxuser', array('ye'=>$ye), "mid='".$mid."' and openid='".$order['openid']."'");
				$logid = $ye;
				break;
			case 'integral':
				$trigger_num = intval($h['trigger_num']);
				if(!in_array($h['trigger_filed'],array('value1','value2','value3','value4','value5','value6','value7','value8'))){
					$isfalse = 1;	
					break;
				}
				if($trigger_num <= 0){
					$isfalse = 1;
					break;
				}
				//会员积分信息
				$userinit = DB::fetch_first('select * from %t where mid=%s and openid=%s',array('wx_integral',$mid,$order['openid']));
				$userInitArr = array();
				if($userinit['id']){
					$userInitArr[$h['trigger_filed']] = $trigger_num + $userinit[$h['trigger_filed']];
					DB::update('wx_integral',$userInitArr,'id='.intval($userinit['id']));
				}else{
					$userInitArr['mid'] = $mid;
					$userInitArr['openid'] = $order['openid'];
					$userInitArr[$h['trigger_filed']] = $trigger_num;
					$userinit['id'] = DB::insert('wx_integral',$userInit,true);
				}
				$logid = $userInitArr[$h['trigger_filed']];
				break;
			default:
				$isfalse = 1;
				break;	
		}
		
		if($isfalse){
			continue;	
		}
		$insert = array();
		$insert = $h;
		unset($insert['id']);
		$insert = array_merge($h,$ih);
		unset($insert['id']);
		
		$insert['mid'] = $mid;
		$insert['oi_id'] = $ih['id'];
		$insert['otrigger_id'] = $h['id'];
		$insert['order_id'] = $id;
		$insert['time_time'] = $order_time;
		$insert['money'] = $order['total_actual_pay'];
		$insert['openid'] = $order['openid'];
		$insert['log_id'] = $logid;
		$insert['inputtime'] = TIME;
		DB::SetMainDB(DB_ESHOP);
		DB::insert("es_otrigger_log", $insert);	
	}
}

//发送优惠券
function discountvoucher_get($id,$mid,$openid){
	//发送优惠券信息
	$r = C::t('#api#eshop')->getDiscountvoucherM($id);

	$sql['coupon_id']			= $id;
	$sql['title']				= $r['title'];
	$sql['description']			= $r['description'];
	$sql['thumb']				= $r['thumb'];
	$sql['price']				= $r['price'];
	$sql['limit_price']			= $r['limit_price'];
	$sql['limit_user']			= $r['limit_user'];
	$sql['btime']				= $r['btime'];
	$sql['etime']				= $r['etime'];
	$sql['limit_btime']			= $r['limit_btime'];
	$sql['limit_etime']			= $r['limit_etime'];
	$sql['isget']				= $r['isget'];
	$sql['no_discount_group']	= $r['no_discount_group'];
	$sql['mid']					= $mid;
	$sql['openid']				= $openid;
	$sql['inputtime'] 			= TIME;
	$sql['status'] 				= 1;
	$sql['display'] 			= 1;
	DB::SetMainDB(DB_ESHOP);
	$logid = DB::insert('es_coupon_log',$sql,true);

	return array('Error'=>0,'Msg'=>'操作成功','id'=>$logid);

}
//触发事件
function trigger_event($id,$mid,$openid){
	if($openid){
		if($id){
			$event = DB::fetch_first('select id,type from %t where mid=%s and id=%d and display=1',array('wx_event',$mid,$id));
        }
        if($event){
			//判断是否是我说的话
		if($event['type'] == 'text'){
			$bind = DB::fetch_first('select * from %t where tablename=%s and type=%s and tableid=%d and mid=%s and display=1',array('wx_bind', 'wx_event', 'text', $event['id'], $mid));
			if($bind) $msg = $bind['content'];
				$msg ? $r = DoCurl('http://10.252.85.65/active_add.php?api=custom_send', array('mid'=>$mid,'openid'=>$openid,'msgtype'=>'text','content'=>$msg)) : '';
			}else{
				$bind = DB::fetch_all('select * from %t where tablename=%s and tableid=%d and mid=%s and display=1 order by turn desc',array('wx_bind', 'wx_event', $event['id'], $mid));
				$msg = array();
				foreach($bind as $v){
					$msg[] = array('title'=>$v['title'],'description'=>$v['content'],'picurl'=>$v['thumb'],'url'=>$v['url']);
				}
				$msg ? $r = DoCurl('http://10.252.85.65/active_add.php?api=custom_send', http_build_query(array('mid'=>$mid,'openid'=>$openid,'msgtype'=>'news','content'=>$msg))) : '';
			}
		}
	}
	return $r;
}

function addmemberlogin($mid,$return_code='FALSE',$login_method='PC_ACCOUNT',$account='',$member_id=0,$return_msg=''){
	if(!$mid||!$return_code) return false;
	if(!DB::CheckTable('common_member_login')) return false;
	if($return_code == 'SUCCESS'){
		if(!$member_id) return false;
	}else{
		if($return_msg=='') return false;	
	}
	$insert = array();
	$insert['mid'] 			= $mid;
	$insert['return_code'] 	= $return_code;
	$insert['login_method'] = $login_method;
	$insert['account'] 		= $account;
	$insert['member_id'] 	= $member_id;
	$insert['return_msg'] 	= $return_msg;
	$insert['clientip'] 	= GetIP();
	$insert['inputtime'] 	= TIME;
	DB::insert('common_member_login',$insert);
}


////API会员验证
//function Api_InitUser($_mid=''){
//    global $_G;
//    if(!$_G['g_authkey']) return 0;
//    list($id, $mid ) = explode(",", SING_auth($_G['g_authkey'],'DECODE',getglobal('cookiepre','config/cookie')));
//    //echo $mid.','.$phone.','.$id;
//    if(!$id || !$mid) return 0;
//    if($_mid != $mid)
//        return 0;
//        //return array('Error'=>2,'Msg'=>'无效密钥');
//    $member = DB::fetch_first('select `id`,`openid`,`unionid` from %t where mid=%s and id=%d',array('common_member',$mid,$id));
//    if($member['id']){
//        $_G[$_mid]['memberid'] = $member['id'];
//        $_G[$_mid]['openid'] = $member['openid'];
//        $_G[$_mid]['unionid'] = $member['unionid'];
//        $_G['member'] = array();
//    }else{
//        //return array('Error'=>2,'Msg'=>'无效密钥或账号不存在');
//    }
//    return 0;
//}
function checkLogin(){
    global $_G,$_mid;
    //var_dump($_G[$_mid]['memberid']);
    if(!$_G[$_mid]['memberid'] || $_G[$_mid]['memberid'] == -1){
        return array('Error'=>2,'Msg'=>'请先登录');
    }
    return 0;
}
//验证数据
function inspectdata($data){
    global $_mid;

    if(!is_array($data) ||!isset($data['sign']) || count($data) <2) return false;
    $temp = $data;
    foreach($temp as $k=>$v){
        if(empty($v) || $k=='sign') unset($temp[$k]);
    }
    $temp[] = $_mid;
    /*if($_mid!='HNMRWGZSVY'){
        $temp = array_values($temp);
        sort($temp);
    }*/
    $tempstr = implode($temp);
    $signature = sha1($tempstr);

    if($data['sign'] == $signature) return true; 
    else return false;
}

//统一处理时间格式 返回数字（时间戳） 
function parseTimeFormat($time = ''){
    if(!$time) return 0;
    if(!is_numeric($time)) $time = strtotime($time);
    return $time;
}

//数组递归使用urldecode解码
function arrayByUrlcode($arr= array()){
    if(empty($arr)){
        return $arr;
    }
    if(is_array($arr)){
        foreach($arr as $k=>$v){
            $arr[$k] = arrayByUrlcode($v);
        }
    }else{
        $arr = urldecode($arr);
    }
    return $arr;
}

//function authMemberId($memberid=0,$method='ENCODE'){
//    if($method == 'ENCODE'){
//        return SING_auth($memberid.','.TIME,$method,getglobal('cookiepre','config/cookie'));
//    }elseif($method == 'DECODE'){
//        list($memberid) = explode(",", SING_auth($memberid,$method,getglobal('cookiepre','config/cookie')));
//        return $memberid;
//    }
//}


function addshareUrl($addopenid=false){
    global $_G,$_mid;
    $memberUrlPre = $openUrlPre ='';
    switch($_G['g_sourcet']){
        case 'pc':
            $memberUrlPre = 'pc_member_'; 
            //$openUrlPre = 'pc_open_'; 
            break;
        case 'app':
            $memberUrlPre = 'app_member_'; 
            //$openUrlPre = 'app_open_'; 
            break;
    }
    $Uopenid = $_G['g_openid']?$_G['g_openid']:$_G[$_mid]['openid'];
    $Usopenid = $_G[$_mid]['openid'];
    
    if(!$Uopenid){
        $Uopenid = $memberUrlPre.$_G[$_mid]['memberid'];
    }/*else{
        $Uopenid = $openUrlPre.$Uopenid;
    }*/
    if(!$Usopenid){
        $Usopenid =$memberUrlPre.$_G[$_mid]['memberid'];
    }/*else{
        $Usopenid = $openUrlPre.$Usopenid;
    }*/
    $shareUrlstr = '';
    if($addopenid){
        $shareUrlstr .= $Uopenid?'&openid='.$Uopenid:0;
    }
    if(!is_weixin()){
        
        $shareUrlstr .= $Usopenid?'&sopenid='.$Usopenid:0;
    }
    return $shareUrlstr?trim($shareUrlstr,'&'):'';
}

/*
	发钱
	mid  		系统中商家标识
	openid 		微信会员id
	amount 		金额（1.00-200.00元之间 单位：分）
	nickname	提供方名称（少于32个字符）
	sendname 	红包发送者名称（少于32个字符）
	actname 	活动名称（少于32个字符）
	wishing 	祝福语（少于128个字符）
	remark 		备注（少于256个字符）
	注意：		所有参数均不能为空
*/
function Eshop_mch_pay($_mid,$_openid, $member_id, $_amount,$_check_name = 'FORCE_CHECK',$_re_user_name = '',$_desc,$_tablename='',$_tableid=''){
	global $_G;
	include libfile('WxPay_PubHelper','class/wxpay3');
	//微支付设置
	DB::SetMainDB(DB_MAIN);
    $wxpay = DB::fetch_first('select AppId,AppSecret,wxpay_paysignkey,wxpay_partnerid,wxpay_partnerkey,apiclient_cert,apiclient_key from %t where mid=%s limit 1', array('wx_apiuser','NICYEBMGHQ'));
//	$wxpay = DB::fetch_first('select AppId,AppSecret,wxpay_paysignkey,wxpay_partnerid,wxpay_partnerkey,apiclient_cert,apiclient_key from %t where mid=%s limit 1', array('wx_apiuser',$_mid));
	foreach($wxpay as $k => $v){
		if(!$v){
			$objErr['return_code'] = 'FAIL';
			$objErr['return_msg'] = '微信支付接入设置错误：缺少参数_'.strtoupper($k);
			$objErr['mid'] 			= $_mid;
			$objErr['_uid'] 		= $_G['_uid'];
			$objErr['uid'] 			= $_G['uid'];
			$objErr['inputtime'] 	= TIME;
			$objErr['openid']   	= $_openid;
			$objErr['amount']   	= $_amount;
			$objErr['tablename'] 	= $_tablename;
			$objErr['tableid'] 		= $_tableid;
			$objErr['member_id']	= $member_id;
			DB::SetMainDB(DB_ESHOP);
			DB::insert('es_mch_pay_log',$objErr);
			return false;
		}
	}
	define('APPID' , $wxpay['AppId']);  						//appid 公众账号的
	define('APPKEY' ,$wxpay['wxpay_paysignkey']); 			//paysign key 申请微信支付返回的
	define('PARTNERID' ,$wxpay['wxpay_partnerid']); 			//财付通商户号
	define('PARTNERKEY',$wxpay['wxpay_partnerkey']);			//通加密串  这个是财付通提供过来的
//	$sslcert_path = APP_ROOT.$wxpay['apiclient_cert'];
//	$sslkey_path = APP_ROOT.$wxpay['apiclient_key'];
    $sslcert_path = $wxpay['apiclient_cert'];
    $sslkey_path = $wxpay['apiclient_key'];
	if(!is_file($sslcert_path) || !is_file($sslkey_path)){
		//载入OSS SDK
		if(!defined('OSSSDK'))	{
			include libfile('oss/sdk','class');
			define('OSSSDK',TRUE);
		}
		$oss_sdk_service = new ALIOSS();
		$oss_sdk_service->set_debug_mode(false);
		$bucket = 'sichem-wx-sert';
	}
	if(!is_file($sslcert_path) && dmkdir(dirname($sslcert_path))){ //本地不存在
		$object = strrchr($sslcert_path,'cert/');
		$options = array(
				ALIOSS::OSS_FILE_DOWNLOAD => $sslcert_path,
			//ALIOSS::OSS_CONTENT_TYPE => 'txt/html',
		);
		$response = $oss_sdk_service->get_object($bucket,$object,$options);
		if(!$response->isOk()){
			return;
		}
	}

	if(!is_file($sslkey_path) && dmkdir(dirname($sslkey_path))){ //本地不存在
		$object = strrchr($sslkey_path,'cert/');
		$options = array(
				ALIOSS::OSS_FILE_DOWNLOAD => $sslkey_path,
			//ALIOSS::OSS_CONTENT_TYPE => 'txt/html',
		);
		$response = $oss_sdk_service->get_object($bucket,$object,$options);
		if(!$response->isOk()){
			return;
		}
	}

	define('SSLCERT_PATH',$sslcert_path);	//通加密串  这个是财付通提供过来的
	define('SSLKEY_PATH',$sslkey_path);	//通加密串  这个是财付通提供过来的

	$unifiedOrder = new UnifiedOrder_pub();

	//订单号
	$billno = PARTNERID.date('YmdHis').$unifiedOrder->createNoncestr(10);

	$bizObj['mch_appid'] 			= APPID;								//公众账号appid
	$bizObj['mchid']				= PARTNERID;							//商户号
	$bizObj['nonce_str']    		= $unifiedOrder->createNoncestr();		//随机数
	$bizObj['partner_trade_no']		= $billno;								//商户订单号
	$bizObj['openid'] 				= $_openid;								//用户openid
	$bizObj['check_name']			= $_check_name;							//是否校验用户姓名
	$bizObj['re_user_name']			= $_re_user_name;						//用户姓名
	$bizObj['amount']				= $_amount;								//付款金额(单位分)
	$bizObj['desc']					= $_desc;								//付款描述
	$bizObj['spbill_create_ip'] 	= $_G['clientip'];						//Ip地址
	$bizObj['sign'] 				= $unifiedOrder->getSign($bizObj);		//生成签名

	$xml = $unifiedOrder->arrayToXml($bizObj);
	$return = $unifiedOrder->postXmlSSLCurl($xml,'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers');
	if($postObj = simplexml_load_string($return, 'SimpleXMLElement', LIBXML_NOCDATA)){
		$objArr['return_code']    	= (string)$postObj->return_code;
		$objArr['return_msg']    	= (string)$postObj->return_msg;
		$objArr['result_code']    	= (string)$postObj->result_code;
		$objArr['err_code']       	= (string)$postObj->err_code;
		$objArr['err_code_des']   	= (string)$postObj->err_code_des;

		$objArr['partner_trade_no'] = (string)$postObj->partner_trade_no;
		$objArr['payment_no'] 		= (string)$postObj->payment_no;
		$objArr['payment_time'] 	= (string)$postObj->payment_time;
		$objArr['payment_time_int'] = $objArr['payment_time']?strtotime($objArr['payment_time']):0;
		$objArr['mch_appid']     	= (string)$postObj->mch_appid;
		$objArr['mchid']         	= (string)$postObj->mchid;

		$objArr['sendxml'] 			= $xml;
		$objArr['returnxml'] 		= $return;

		$objArr['openid']        	= $_openid;
		$objArr['amount']   		= $_amount;
		$objArr['mid'] 				= $_mid;
		$objArr['_uid'] 			= $_G['_uid'];
		$objArr['uid'] 				= $_G['uid'];
		$objArr['tablename']		= $_tablename;
		$objArr['tableid'] 			= $_tableid;
		$objArr['inputtime'] 		= TIME;
		$objArr['member_id']		= $member_id;

		DB::SetMainDB(DB_ESHOP);
		DB::insert('es_mch_pay_log',$objArr);
		if(strtolower($objArr['result_code']) == 'success') return true;
		else return false;
	}else{
		$objErr['return_code'] = 'FAIL';
		$objErr['return_msg'] = '传递错误';
		$objErr['openid']        	= $_openid;
		$objErr['amount']   		= $_amount;
		$objErr['mid'] 				= $_mid;
		$objErr['_uid'] 			= $_G['_uid'];
		$objErr['uid'] 				= $_G['uid'];
		$objErr['tablename']		= $_tablename;
        $objErr['err_code_des']		= $sslcert_path.$sslcert_path;
		$objErr['tableid'] 			= $_tableid;
		$objErr['inputtime'] 		= TIME;
		$objErr['member_id']		= $member_id;
		DB::SetMainDB(DB_ESHOP);
		DB::insert('es_mch_pay_log',$objErr);
		return false;

	}
}


/*
 * 将所有接入为空的值 转成对应类型的空值  
 */
function convertNullType($val){
    if(!empty($val) && is_array($val)){
        foreach($val as $k=>$v){
            $val[$k] = convertNullType($v);
        }
    }else if(empty($val)){
        if(is_array($val)){
            $val = array();
        }else if(is_numeric($val)){
            $val = 0;
        }else if(is_string($val)){
            $val = '';
        }else if(is_bool($val)){
            $val = false;
        }else{
            $val = null;
        }
    }
    return $val;
}


//原微信curl 方法  远程访问接口用
function active_curl($url, $post_data = array()) {
    try {
        global $mid;
        //获取Cookie
        $clientkey = getcookie('memberKey_'.$mid);
        //转换Cookie
        list(,,,$pctoken) = explode("\t", SING_auth($clientkey,'DECODE',getglobal('cookiepre','config/cookie')));



        if(is_array($post_data)){
            if($pctoken){
                $post_data['pctoken'] = $pctoken;
            }
            $post_data['sourcet'] = 'pc';
        }else{
            if($pctoken){
                $post_data .= strlen($post_data)>0?'&':'';
                $post_data .= http_build_query(array('pctoken'=>$pctoken));
            }
            $post_data .= strlen($post_data)>0?'&':'';
            $post_data .= http_build_query(array('sourcet'=>'pc'));
        }
        $get_content = DoCurl($url, $post_data);
//        if(strpos($url,'storeorderback')!==false){
//            var_dump($get_content);
//        }
        return json_decode($get_content, true);
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
}








//自动返回access_token 授权返回 和 未授权返回
function active_check_access_token($mid = '', $qz = 0) {
    if (!$mid) {
        global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取access_token 参数MID丢失');
    }

    $apiuser = active_get_apiuser($mid);
    //var_dump($apiuser);
    if (is_array($apiuser) && $apiuser['errcode']) {
        return $apiuser;
    }



    if ($apiuser['isauthorize']) {
        $access_token = active_get_authorizer_access_token($mid,$apiuser['AppIdC'] ,$qz);
    } else {

        $access_token = active_GetAccess_token($mid, $qz);

    }
    return $access_token;
}


function active_GetAccess_token($mid = '', $qz = 0) {
    global $_G;
    //$qz = 1;
    if (!$mid) {
        //global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取access_token 参数MID丢失');
    }
    $losetime = TIME - 6000;
    //$d = memory('get', 'wx-access_token-' . $mid);

    if (!$d || $d['inputtime'] < $losetime || $qz) {
        //DB::query("delete FROM %t where mid=%s and `inputtime` <= %d", array('wx_access_token',$mid ,TIME-6000));
        //DB::SetMainDB(3);
        $d = DB::fetch_first("select * from %t where mid=%s and `inputtime` > %d", array('wx_access_token', $mid, $losetime));
        if ($d && $d['inputtime'] > $losetime && !$qz) {
            //memory('set', 'wx-access_token-' . $mid, $d);
        } else {

            //memory('rm', 'wx-access_token-' . $mid);
            //DB::SetMainDB(3);
            DB::query("delete FROM %t where mid=%s ", array('wx_access_token', $mid));
            $apiuser = active_get_apiuser($mid);
            if (is_array($apiuser) && $apiuser['errcode']) {
                return $apiuser;
            }
            if (!$apiuser['AppId']) {
                return array('errcode' => 1, 'errmsg' => '未设置AppId');
            }
            if (!$apiuser['AppSecret']) {
                return array('errcode' => 1, 'errmsg' => '未设置AppSecret');
            }

            $d = active_curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$apiuser['AppId']."&secret=".$apiuser['AppSecret']);

            if (is_array($d) && $d['access_token']) {
                //DB::SetMainDB(3);
                DB::insert('wx_access_token', array('access_token' => $d['access_token'], 'mid' => $mid, 'inputtime' => TIME));
            }
        }
    }
    if (is_array($d) && $d['errcode']) {
        return $d;
    } elseif ($d) {
        return $d['access_token'];
    } else {
        return array('errcode' => 1, 'errmsg' => 'access_token获取失败');
    }
}
//获取授权方 授权令通过刷新令牌获取信息    授权公众号 的 access_token
function active_get_authorizer_access_token($mid = '', $AppIdC = 1,$qz = 0) {
    global $_G;
    if (!$mid) {
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '参数MID丢失');
    }
    $AppConfig = $_G['config']['AppConfig'][$AppIdC];
    $appid = $AppConfig['AppID'];

    if(!$appid || !$mid){
        return array('errcode' => 300, 'errmsg' => 'NO APPID MID');
    }

    //$d = memory('get', 'wx-authorize_access_token-' . $mid . '-' . $appid);
    if (!$d || (TIME - $d['inputtime'] > 6000) || $qz) {
        $d = DB::fetch_first('select * from %t where mid=%s', array('wx_authorize_access_token', $mid));
        if ($d && (TIME - $d['inputtime']) < 6000 && !$qz) {
            // memory('set', 'wx-authorize_access_token-' . $mid . '-' . $appid, $d);
            return $d['authorizer_access_token'];
        }
        //memory('rm', 'wx-authorize_access_token-' . $mid . '-' . $appid);
        DB::delete('wx_authorize_access_token', " mid='" . $mid . "'");

        $component_access_token = active_get_component_access_token($AppIdC);
        if (is_array($component_access_token) && $component_access_token['errcode']) {
            return $component_access_token;
        }
        $post_data['component_appid'] = $appid;
        $apiuser = active_get_apiuser($mid, array('AppId', 'authorizer_refresh_token'));
        if (is_array($apiuser) && $apiuser['errcode']) {
            return $apiuser;
        }
        $post_data['authorizer_appid'] = $apiuser['AppId'];
        $post_data['authorizer_refresh_token'] = $apiuser['authorizer_refresh_token'];

        $d = active_curl('https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . $component_access_token, json_encode($post_data));
        /*if($_G[$_GET['mid']]['openid'] == 'o6aCkjgr1DZ61bE2hQosrpLteYlk'){
             //echo (TIME - $d['inputtime']);
             echo '1';
             //var_dump($d);
             //var_dump($component_access_token);
             //echo $d['inputtime'].'#';
             //var_dump($apiuser);
         }*/
        if ($d['authorizer_access_token']) {
            $insert_act = array();
            $insert_act['mid'] = $mid;
            //$insert_act['appid'] = $appid;
            $insert_act['authorizer_access_token'] = $d['authorizer_access_token'];
            $insert_act['authorizer_refresh_token'] = $d['authorizer_refresh_token'];
            $insert_act['expires_in'] = $d['expires_in'];
            $insert_act['inputtime'] = TIME;
            DB::insert('wx_authorize_access_token', $insert_act);
        }
        active_addAuthorize_log($d, 'api_authorizer_token', $appid, intval($d['errcode']), $d['authorizer_access_token']);
    }
    if (is_array($d) && $d['errcode']) {
        return $d;
    } elseif ($d) {
        return $d['authorizer_access_token'];
    } else {
        return array('errcode' => 1, 'errmsg' => 'authorizer_access_token获取失败');
    }
}



//获取 企业信息 apiuser
function active_get_apiuser($mid = '', $zd = '') {
    if (!$mid) {
        global $_G;
        $mid = $_G['g_mid'];
    }
    if (!$mid) {
        return array('errcode' => 1, 'errmsg' => '获取公众号信息 参数MID丢失');
    }
    //$d = memory('get', 'wx-apiuser-' . $mid);

    if (!$d) {
        //DB::setRead();
        $d = DB::fetch_first('select * from %t where mid=%s', array('wx_apiuser', $mid));
        /*if ($d)
            memory('set', 'wx-apiuser-' . $mid, $d);*/
    }
    if (!$d) {
        return array('errcode' => 1, 'errmsg' => '获取公众号信息失败');
    }
    $data = array();
    if (empty($zd)) {
        $data = $d;
    } else {
        if (!is_array($zd)) {
            $zd = explode(',', $zd);
        }
        foreach ($zd as $k => $v) {
            $data[$v] = $d[$v];
        }
        if (count($zd) === 1) {
            $data = current($data);
        }
    }
    return $data;
}


/*	截取字符串
*	$sourcestr 	需要截取的字符串
*	$cutlength	截取的长度
*	$nohtml		是否带html标签 默认 不带
*	$laststr	截取长度小于字符串长度是 后面加的后缀 默认 ...
*/
function Web_substr_cut_str($sourcestr,$cutlength=0,$nohtml=1,$laststr='...'){
    if($nohtml) $sourcestr = strip_tags($sourcestr,'');
    $returnstr='';
    $i=0;
    $n=0;
    $str_length=strlen($sourcestr);//字符串的字节数
    while ((($n < $cutlength)||!$cutlength) and ($i <= $str_length)){
        $temp_str=substr($sourcestr,$i,1);
        $ascnum=ord($temp_str);//得到字符串中第$i位字符的ascii码
        if ($ascnum>=224){//如果ASCII位高与224，
            $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i=$i+3; //实际Byte计为3
            $n++; //字串长度计1
        }elseif ($ascnum>=192){//如果ASCII位高与192，
            $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i=$i+2; //实际Byte计为2
            $n++; //字串长度计1
        }elseif ($ascnum>=65 && $ascnum<=90){//如果是大写字母，
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1; //实际的Byte数仍计1个
            $n++; //但考虑整体美观，大写字母计成一个高位字符
        }else{//其他情况下，包括小写字母和半角标点符号，
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1; //实际的Byte数计1个
            $n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length>$i){
        $returnstr = $returnstr . $laststr;//超过长度时在尾处加上后缀
    }
    return $returnstr;
}
function getEwm($mid,$use){
	$ticked = DB::fetch_first('select * from %t where mid=%s and `use`=%s and type=1', array('wx_ticket',$mid,$use));
	if($ticked['ticket']){
		$sence = get_scene_byewm($mid,$ticked['ticket']);
		$ticked['senceid'] = $sence['id'];
	}
	return $ticked;
}
function get_scene_byewm($mid,$ewm){
	if(!$mid) return false;
	if(!$ewm) return false;
	$scene = DB::fetch_first('select * from %t where thumb = %s and mid=%s and display=1 and status=1 order by id desc',array('wx_scene',$ewm,$mid));
	if(!$scene['id']) return false;
	return $scene;
}

function fetchScanDir($prefix = 'dbt_order',$dir = 'module/api/class/dbt' , $ext='.php'){
	$r = array();
	$systemDir = APP_ROOT.DIRECTORY_SEPARATOR.$dir;
	//$systemDir = $dir;
	if(is_dir($systemDir)){
		if($files = scandir($systemDir)) {
			$isDbt = substr($prefix,0,4) == 'dbt_';
			$fixLen = strlen($prefix);
			$extLen = strlen($ext);
			foreach($files as $k=>$v){
				if($prefix && $prefix == substr($v,0,$fixLen)){
					if($extLen && $ext == substr($v,$extLen*-1) ){
						$r[] = array(
								'fullName' =>$v,
								'fixName' => substr($v,$fixLen,$extLen*-1),
								'dbtName' => $isDbt?substr($v,4,$extLen*-1):''
						);
					}

				}

			}
		}
	}
	return $r;
}

/*------------同步部分 wxweb function_eb 是主方法（只修改这部分）  其他地方在这复制------*/

/*
 *  设置读取缓存 固定时间自动丢弃并删除缓存
 */
function autoMemory($method,$fileName,$data=Null){
	if(!$method || !$fileName){
		return false;
	}
	$autoUpdateTime = 86400; //固定时间自动更新缓存
	switch($method){
		case 'get':
			$return = memory('get',$fileName);
			if($return[1] && ($return[1] + $autoUpdateTime) >= TIME){
				return $return[0];
			}elseif($return){
				memory('rm',$fileName);
			}
			break;
		case 'set':
			$setData = array($data,TIME);
			memory('set',$fileName,$setData);
			break;
	}
	return false;
}

/*------------------------*/

/*
	申请退款
	mid  			系统中商家标识
	transid 		微信订单号（少于28个字符）
	out_trade_no	商户系统内部的订单号（少于32个字符）
	out_refund_no 	商户退款单号（少于32个字符）
	total_fee 		订单总金额，单位为分，只能为整数
	refund_fee 		退款总金额，订单总金额，单位为分，只能为整数
	注意：			所有参数均不能为空
*/
function wxRefund($_mid,$_transid,$_table,$_out_trade_no,$_total_fee,$_refund_fee,$isId=false){
	global $_G;

	if(!$_mid || !$_transid || !$_out_trade_no){
		//echo array($_mid,$_transid,$_out_trade_no);
		return false;
	}

	include_once libfile('wxpay/api','class');

	$WxPayApi = new WxPayApi();

	$WxPayRefund = new WxPayRefund();

	//设置商户系统内部的订单号,transaction_id、out_trade_no二选一，如果同时存在优先级：transaction_id> out_trade_no
	$WxPayRefund->SetTransaction_id($_transid);
	//设置商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔
	$_out_refund_no = 'R'.date('YmdHis').rand_str(7,true);
	$WxPayRefund->SetOut_refund_no($_out_refund_no);
	//设置订单总金额，单位为分，只能为整数，详见支付金额
	$WxPayRefund->SetTotal_fee($_total_fee);
	//设置退款总金额，订单总金额，单位为分，只能为整数，详见支付金额
	$WxPayRefund->SetRefund_fee($_refund_fee);
	//设置操作员帐号, 默认为商户号
	$WxPayRefund->SetOp_user_id(WxPayConfig::getMCHID());

	//判断证书
	$sslcert_path = APICLIENTCERT;
	$sslkey_path = APICLIENTKEY;
//        if($_GET['debug']==1){
//
//            var_dump($_mid);
//        }
//	if($_mid=='OIJRMQJHNM'){
//            var_dump(APICLIENTCERT);
//            var_dump(APICLIENTKEY);
//            exit;
//        }
	if(!is_file($sslcert_path) || !is_file($sslkey_path)){
		//载入OSS SDK
		if(!defined('OSSSDK'))	{
			include libfile('oss/sdk','class');
			define('OSSSDK',TRUE);
		}
		$oss_sdk_service = new ALIOSS();
		$oss_sdk_service->set_debug_mode(false);
		$bucket = 'sichem-wx-sert';
	}

	if(!is_file($sslcert_path) && dmkdir(dirname($sslcert_path))){ //本地不存在
		$object = strrchr($sslcert_path,'cert/');
		$options = array(
				ALIOSS::OSS_FILE_DOWNLOAD => $sslcert_path,
			//ALIOSS::OSS_CONTENT_TYPE => 'txt/html',
		);
		$response = $oss_sdk_service->get_object($bucket,$object,$options);
		if(!$response->isOk()){
			//echo 'No1';
			return;
		}
	}

	if(!is_file($sslkey_path) && dmkdir(dirname($sslkey_path))){ //本地不存在
		$object = strrchr($sslkey_path,'cert/');
		$options = array(
				ALIOSS::OSS_FILE_DOWNLOAD => $sslkey_path,
			//ALIOSS::OSS_CONTENT_TYPE => 'txt/html',
		);
		$response = $oss_sdk_service->get_object($bucket,$object,$options);
		if(!$response->isOk()){
			//echo 'No2';
			return;
		}
	}

	//执行退款
	$return = WxPayApi::refund($WxPayRefund);

	//var_dump($return);exit;
	if($return){

		$objArr['return_code']  	 = $return['return_code'];
		$objArr['return_msg']    	 = $return['return_msg'];
		$objArr['result_code']   	 = $return['result_code'];
		$objArr['err_code']    	 	 = $return['err_code'];
		$objArr['err_code_des']    	 = $return['err_code_des'];
		$objArr['mch_id']        	 = $return['mch_id'];
		$objArr['appid']         	 = $return['appid'];
		$objArr['transaction_id'] 	 = $return['transaction_id'];
		$objArr['out_trade_no']  	 = $return['out_trade_no'];
		$objArr['out_refund_no'] 	 = $return['out_refund_no'];
		$objArr['refund_id']   	  	 = $return['refund_id'];
		//$objArr['refund_channel'] 	 = $return['refund_channel'];
		$objArr['refund_fee']		 = $return['refund_fee'];
		$objArr['coupon_refund_fee'] = $return['coupon_refund_fee'];

		$objArr['xml'] = json_encode($return);

		$objArr['mid'] = $_mid;

		$objArr['_uid'] = $_G['_uid'];

		$objArr['uid'] = $_G['uid'];

		$objArr['inputtime'] = TIME;

		$objArr['tablename'] = $_table;

		$objArr['tableid'] = $_out_trade_no;

		$objArr['id'] = $_out_refund_no;

		DB::SetMainDB(DB_MAIN);
		DB::insert('wx_wxrefund',$objArr);

		if(strtolower($objArr['result_code']) == 'success'){
			if($isId){
				return $_out_refund_no;
			}else{
				return true;
			}

		}

	}else{

		$objErr['id'] = $_out_refund_no;

		$objErr['return_code'] = 'FAIL';

		$objErr['return_msg'] = '传递错误';

		$objErr['result_code'] = 'FAIL';

		$objErr['mid'] = $_mid;

		$objErr['_uid'] = $_G['_uid'];

		$objErr['uid'] = $_G['uid'];

		$objErr['inputtime'] = TIME;

		$objErr['tablename'] = $_table;

		$objErr['tableid'] = $_out_trade_no;

		DB::SetMainDB(DB_MAIN);
		DB::insert('wx_wxrefund',$objErr);
		//echo 'No4';
		return false;

	}
}
